﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using WcfServiceBomberman.Models;

namespace WcfServiceBomberman.Databases
{
    [Serializable()]
    public class Database
    {
        public List<Player> players;

        [NonSerialized()]
        private string filename;

        // constructor when not loaded
        private void construct()
        {
            players = new List<Player>();
        }

        public static Database load(string filename)
        {
            //File.Delete(filename);
            Database database;
            if (!File.Exists(filename))
            {
                database = new Database();
                database.filename = filename;
                database.construct();
                return database;
            }

            Stream TestFileStream = File.OpenRead(filename);
            BinaryFormatter deserializer = new BinaryFormatter();
            database = (Database)deserializer.Deserialize(TestFileStream);
            database.filename = filename;
            TestFileStream.Close();
            return database;
        }

        public void save()
        {
            Stream TestFileStream = File.Create(filename);
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(TestFileStream, this);
            TestFileStream.Close();
        }
    }
}
